package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"time"

	"../util"
)

func GetDoc(filename, latnId string) ([]byte, error) {
	url := BuildUrl(filename, latnId)
	response, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}
	if response.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("server response: %v. statuscode: %v.", string(body), response.StatusCode)
	}
	return body, nil
}

func BuildUrl(filename, latnId string) string {
	timestamp := strconv.FormatInt(time.Now().UnixNano()/1000/1000, 10)
	text := "crmlog" + "crmlog1452" + timestamp
	signature := util.MD5([]byte(text))
	url := "http://132.121.82.193:8085/REST/docServiceV2?"
	url = url + "method=get&organId=2222&busiType=1&staffNo=GZTEST200&version=001&"
	url = url + "appId=crmlog&password=crmlog1452&"
	url = url + fmt.Sprintf("timestamp=%s&", timestamp)
	url = url + fmt.Sprintf("signature=%s&", signature)
	url = url + fmt.Sprintf("latnId=%s&", latnId)
	url = url + fmt.Sprintf("filename=%s", filename)
	return url
}
